/*
 * Copyright (c) 2009.
 * nick@tmro.net
 */
package net.tmro.loko.webservices.json.config;

import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
import net.tmro.loko.domain.PersistentEntity;
import net.tmro.loko.domain.category.Category;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import java.util.*;

/**
 * @author japod See http://blogs.sun.com/japod/entry/better_json_available_in_jersey
 *         and also  http://blogs.sun.com/enterprisetechtips/entry/configuring_json_for_restful_web
 */
@Provider
public final class JAXBContextResolver implements ContextResolver<JAXBContext> {

    private final JAXBContext context;

    private final Set<Class> types;

    private final Class[] myTypes = {PersistentEntity.class, Category.class};

    public JAXBContextResolver() throws Exception {
        Map<String, Object> props = new HashMap<String, Object>();

        final JSONConfiguration jsonConfiguration = JSONConfiguration.mappedJettison().build();

        this.types = new HashSet<Class>(Arrays.asList(myTypes));
        this.context = new JSONJAXBContext(jsonConfiguration, myTypes);
    }


    public JAXBContext getContext(Class<?> objectType) {
        return (types.contains(objectType)) ? context : null;
    }
}